// JsonParser.java
package com.example;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JsonParser {
    public static List<Note> parseJsonFiles(String directoryPath) throws IOException {
        List<Note> notes = new ArrayList<>();
        File directory = new File(directoryPath);

        if (!directory.isDirectory()) {
            throw new IllegalArgumentException("Invalid directory path");
        }

        ObjectMapper mapper = new ObjectMapper()
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        for (File file : directory.listFiles((dir, name) -> name.endsWith(".json"))) {
            try {
                // 直接读取整个 JSON 文件为 JsonNode
                JsonNode rootNode = mapper.readTree(file);

                // 提取 data.notes 节点
                JsonNode notesNode = rootNode.path("data").path("notes");

                // 遍历 notes 数组
                if (notesNode.isArray() && notesNode.size() > 0) {
                    for (JsonNode noteNode : notesNode) {
                        Note note = mapper.treeToValue(noteNode, Note.class);
                        notes.add(note);
                    }
                }
            } catch (IOException e) {
                System.err.println("Error parsing file: " + file.getName());
                e.printStackTrace();
            }
        }
        return notes;
    }
}